package com.guigu.eduservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.guigu.common.utils.R;
import com.guigu.eduservice.entity.Equipment;
import com.guigu.eduservice.entity.EquipmentImage;
import com.guigu.eduservice.entity.EquipmentType;
import com.guigu.eduservice.entity.EquipmentVideo;
import com.guigu.eduservice.service.EquipmentImageService;
import com.guigu.eduservice.service.EquipmentService;
import com.guigu.eduservice.service.EquipmentTypeService;
import com.guigu.eduservice.vo.AuditVo;
import com.guigu.eduservice.service.EquipmentVideoService;
import com.guigu.eduservice.vo.EqVo;
import com.guigu.eduservice.vo.EquipmentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 设备表（存储卖家发布的二手机械信息） 前端控制器
 * </p>
 *
 * @author janecraft
 * @since 2025-09-27
 */
@RestController
@RequestMapping("/eduservice/equipment")
public class EquipmentController {
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private EquipmentImageService equipmentImageService;
    @Autowired
    private EquipmentVideoService equipmentVideoService;
    @Autowired
    private EquipmentTypeService equipmentTypeService;

    @GetMapping("/getAll")
    public List<Equipment> getAll( @RequestParam(required = false) Long typeId) {

        return equipmentService.getAll(typeId);
    }

    @PostMapping("/page/{pageNo}/{pagesize}")
    public PageInfo<Equipment> page(@PathVariable Integer pageNo, @PathVariable Integer pagesize, @RequestBody EqVo vo) {
        return equipmentService.page(pageNo, pagesize,vo);
    }

    @GetMapping("/getById/{id}")
    public Equipment getById(@PathVariable Long id) {
        return equipmentService.getById(id);
    }

    @PostMapping("/add")
    public R add(@RequestBody Equipment equipment) {
        //这个设备里面参数可以有视频，图片
        //先将设备保存进数据库，再拿到已经赋值了的图片列表和视频列表
        Equipment equipment1 = equipmentService.addImageV(equipment);
        //判断是否成功，如果成功就返回设备对象，没有成功就返回null
        if (equipment1 == null){
            return R.error().data("data", null);
        }
        //拿到equipment1里面的视频列表与图片列表，判断是否为空
        EquipmentVideo videos = equipment1.getEquipmentVideo();
        List<EquipmentImage> images = equipment1.getEquipmentImages();
        if (videos != null ) {
            //如果不为空就将他插入数据库
            boolean b = equipmentVideoService.save(videos);
            if (!b) {
                return R.error().data("data", null);
            }
        }
        if (images != null && !images.isEmpty()) {
            //如果不为空就将他批量插入数据库
            boolean b = equipmentImageService.saveBatch(images);
            if (!b) {
                return R.error().data("data", null);
            }
        }
        return R.ok().data("data", equipment1);

    }

    @GetMapping("/getCollectionId/{equipmentId}")
    public List<Equipment> getCollectionId(@PathVariable Long equipmentId) {
        System.out.println("equipment_id:" + equipmentId);
        // 1. 先查出设备（用 user_id 或任意条件）
        QueryWrapper<Equipment> eqWrapper = new QueryWrapper<>();
        eqWrapper.eq("equipment_id", equipmentId);
        List<Equipment> equipments = equipmentService.list(eqWrapper);
        if (equipments.isEmpty()) return equipments;

        // 2. 用 equipment_id 去查第1张图（按序号升序）
        for (Equipment eq : equipments) {
            QueryWrapper<EquipmentImage> imgWrapper = new QueryWrapper<>();
            imgWrapper.eq("equipment_id", eq.getEquipmentId())
                    .orderByAsc("sort")
                    .last("LIMIT 1");
            EquipmentImage firstImage = equipmentImageService.getOne(imgWrapper, false);
            eq.setEquipmentImages(firstImage == null ? Collections.emptyList() : Arrays.asList(firstImage));


        }
        System.out.println("equipments:" + equipments);
        return equipments;

    }
    @GetMapping("/getByIdImageV/{id}")//根据设备ID查询设备，并且加入了图片视频
    public Equipment getByIdImageV(@PathVariable Long id) {
        return equipmentService.getByIdImageV(id);
    }

    @PostMapping("/equipmentPage/{pageNo}/{pagesize}")
    public PageInfo<Equipment> equipmentPage(@PathVariable Integer pageNo, @PathVariable Integer pagesize, @RequestBody EqVo vo) {
        return equipmentService.EquipmentPage(pageNo, pagesize,vo);
    }
    @PostMapping("/audit/{id}")
    public boolean audit(@PathVariable Long id, @RequestBody AuditVo auditVo) {
        return equipmentService.audit(id, auditVo);
    }

    @PostMapping("/queryEquipment")
    public R queryEquipment(@RequestBody EquipmentVo vo) {
        System.out.println("进入分页查询面");
        List<Equipment> list = equipmentService.queryEquipment( vo);
        System.out.println("接收到的======="+list);
        return R.ok().data("list",list);
    }

    //根据用户ID查询设备
    @GetMapping("/getEquipmentByUserId/{userId}")
    public R getEquipmentByUserId(@PathVariable Long userId) {
        List<Equipment> list = equipmentService.getEqByUserId(userId);
        return list == null ? R.error() : R.ok().data("list", list);
    }

    /**
     * 前台-根据登录的用户去查询自己出售的设备信息
     * */
    @GetMapping("/selectEquipmentByUserId/{id}/{pageNum}/{pageSize}")
    public  R  selectEquipmentByUserId(@PathVariable("id") Long id,@PathVariable("pageNum") Integer pageNum,
                                       @PathVariable("pageSize") Integer pageSize){

        //根据用户id查询设备信息
        QueryWrapper<Equipment> equipmentQueryWrapper = new QueryWrapper<>();
        equipmentQueryWrapper.eq("user_id", id);
        equipmentQueryWrapper.orderByDesc("release_time");
        List<Equipment> list = equipmentService.list(equipmentQueryWrapper);

        for (int i=0;i<list.size();i++){
            Equipment equipment = list.get(i);

            //根据设备类型id去查询设备类型表
            EquipmentType equipmentType = equipmentTypeService.getById(equipment.getTypeId());
            equipment.setTypeName(equipmentType.getTypeName());

            //根据设备id查询设备图片
            QueryWrapper<EquipmentImage> equipmentImageQueryWrapper = new QueryWrapper<>();
            equipmentImageQueryWrapper.eq("equipment_id",equipment.getEquipmentId());
            List<EquipmentImage> list1 = equipmentImageService.list(equipmentImageQueryWrapper);
            if (!list1.isEmpty()) {
                // 获取第一个设备图片
                EquipmentImage firstImage = list1.get(0);
                equipment.setImageUrl(firstImage.getImageUrl());
            }
        }

        int total = list.size();
        int startIndex = (pageNum - 1) * pageSize;

        // 边界检查：确保 startIndex 不超过总数据量
        if (startIndex >= total) {
            // 如果起始索引超出范围，返回空列表
            return R.ok()
                    .data("list", new ArrayList<>())
                    .data("total", total);
        }

        int endIndex = Math.min(startIndex + pageSize, total);
        List<Equipment> equipmentList = list.subList(startIndex, endIndex);

        return R.ok()
                .data("equipmentList", equipmentList)
                .data("total", total);
    }

    @PutMapping("/updateEquipmentStatusToTwo/{id}")
    public  R updateEquipmentStatusToTwo(@PathVariable("id") Integer id){

        Equipment byId = equipmentService.getById(id);

        byId.setStatus(2);

        boolean b = equipmentService.updateById(byId);

        if (b==true)
            return R.ok().code(20000).message("修改成功").data("success", true);
        return R.error().code(20001).message("修改失败").data("success", false);
    }

    /**
     * 前台-根据设备id去修改设备的状态为已上架
     * */
    @PutMapping("/updateEquipmentStatusToOne/{id}")
    public  R updateEquipmentStatusToOne(@PathVariable("id") Integer id){

        Equipment byId = equipmentService.getById(id);

        byId.setStatus(1);

        boolean b = equipmentService.updateById(byId);

        if (b==true)
            return R.ok().code(20000).message("修改成功").data("success", true);
        return R.error().code(20001).message("修改失败").data("success", false);
    }

    @PutMapping("/shelf/{equipmentId}")
    public int shelf(@PathVariable int equipmentId, @RequestBody EqVo vo){
        return equipmentService.shelf(equipmentId, vo);
    }
}
